<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="商品名称" prop="goodName">
        <el-input
          v-model="queryParams.goodName"
          placeholder="请输入供应商商品id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="创建者" prop="createUser">
        <el-input
          v-model="queryParams.createUser"
          placeholder="请输入创建者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:purchase:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:purchase:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:purchase:remove']"
        >删除</el-button>
      </el-col> -->


      <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleConfirmOrderAdd"
          v-if="isDisplayed"
        >下单</el-button>


      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- <span>采购总额：1000.01</span> -->
    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange" row-key="goodId"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="${comment}" align="center" prop="id" /> -->
      <el-table-column label="商品名称" align="center" prop="goodName" />
      <el-table-column label="商品供应商" align="center" prop="createrName" />
      <el-table-column label="商品单价" align="center" prop="tradePrice" />
      <el-table-column label="采购数量" align="center" prop="counts" />
      <el-table-column label="总计" align="center" prop="counts" >

        <template slot-scope="scope">
          <span>{{ parseFloat(scope.row.tradePrice  *  scope.row.counts).toFixed(2)  }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="采购店铺" align="center" prop="storeName" />
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <!-- <el-table-column label="采购者" align="center" prop="createUser" /> -->
      <el-table-column label="采购时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog
        title="提示"
        :visible.sync="orderOpen"
        width="30%" >
        <span>您总共选择了{{ goodorderCount }} 件商品;  总价为: {{ totalPrice }} 元； 确认要下单吗?</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="orderOpen = false">取 消</el-button>
          <el-button type="primary" @click="confirmOrderAdd">确 定</el-button>
        </span>
</el-dialog>


    <!-- 添加或修改商品采购对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="供应商商品id" prop="goodId">
          <el-input v-model="form.goodId" placeholder="请输入供应商商品id" />
        </el-form-item>
        <el-form-item label="创建者" prop="createUser">
          <el-input v-model="form.createUser" placeholder="请输入创建者" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item> -->
        <el-form-item label="采购数量" prop="counts">
          <el-input v-model="form.counts" placeholder="请输入采购数量" />
        </el-form-item>
        <!-- <el-form-item label="店铺" prop="storeId">
          <el-input v-model="form.storeId" placeholder="请输入店铺" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- <div class="footer row-end">
      <el-button type="primary" size="medium" style="margin-right: 50px ;" @click="toShoppingCar">购物车<i class="el-icon-s-goods el-icon--right"></i></el-button>
    </div> -->
  </div>
</template>

<script>
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase ,handleConfirmOrdersAdd} from "@/api/fx/purchase";
import Cookies from "js-cookie";

export default {
  name: "Purchase",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //下单所选商品
      resultParam:{
       // storeId: 4, //门店id
        remark: "采购下单", //备注
        deliveryType: 1, //配送方式（1普通配送，2加急配送）
        deliveryCost: "0", //配送费用
      },
      totalPrice: 0,
      goodorderCount: 0,
      // 总条数
      total: 0,
      // 商品采购表格数据
      purchaseList: [],
      purchaseOrderSelectList: [],
      purchaseOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      orderOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodName: null,
        createUser: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //是否运行新增
      isDisplayed:false
    };
  },
  created() {
    this.getList();

    const roles = JSON.parse(Cookies.get("roles"));
    roles.forEach(item=>{
      if(item== 'store'){
        this.isDisplayed = true
      }
    })
  },
  methods: {
    //跳转购物车
    toShoppingCar() {
      this.$router.push({
        // name: 'index_purchase'
        path: '/good/index_purchase'
      })
    },
    /** 查询商品采购列表 */
    getList() {
      this.loading = true;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = this.handleTree(response.rows, "goodId");
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodId: null,
        createTime: null,
        createUser: null,
        remark: null,
        counts: null,
        storeId: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.log(selection);
      this.purchaseOrderSelectList=selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    handleConfirmOrderAdd() {
      this.totalPrice =0;
      this.goodorderCount=0;
      this.purchaseOrderList=[];
      this.purchaseOrderSelectList.forEach((item, index) => {
           const itemParm={
           }
          itemParm.id=item.id;
          itemParm.goodId=item.goodId;
          itemParm.remark=item.remark;
          itemParm.counts=item.counts;
          itemParm.storeId=item.storeId;
          this.totalPrice = this.totalPrice + item.counts*item.tradePrice;
          this.goodorderCount= this.goodorderCount+item.counts;
          if(this.resultParam.storeId){
          }else{
            this.resultParam.storeId  =item.storeId;
          }
          this.purchaseOrderList.push(itemParm);
				});
        this.resultParam.purchaseList=this.purchaseOrderList;
        if( this.goodorderCount==0){
          this.$message.error("您未选择商品，不能下单");
        }else{
            this.orderOpen=true;
        }


    },
    confirmOrderAdd(){
      handleConfirmOrdersAdd(this.resultParam).then(response => {
              this.$modal.msgSuccess("下单成功");
              this.getList();
              this.orderOpen = false;
            });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品采购";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchase(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品采购";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePurchase(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchase(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品采购编号为"' + ids + '"的数据项？').then(function() {
        return delPurchase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/purchase/export', {
        ...this.queryParams
      }, `purchase_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
.footer {
  width: 100%;
  margin-top: 200px;
}
.row-end {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-end;
  align-items: center;
}
</style>
